package com.wuye.controller;

import com.wuye.model.User;
import com.wuye.model.option.*;
import com.wuye.model.repair.RepairPerson;
import com.wuye.model.repair.RepairState;
import com.wuye.repository.*;
import com.wuye.web.Pagination;
import com.wuye.web.ST;
import com.wuye.web.SessionHandler;
import com.wuye.web.UserSession;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jiawenlong on 2016/8/1.
 * <p/>
 * SQL：获取每个问题的每个答案的个数
 * select contT.id ,sum(CASE contT.answer when 1 then  contT.cont else 0 end)as answer1 ,sum(CASE contT.answer when 2 then  contT.cont else 0 end)as answer2 ,sum(CASE contT.answer when 3 then  contT.cont else 0 end)as answer3
 * from (select count(*) as cont,answer,c.id from testC,(SELECT id from testC ) c  where questionId=c.id GROUP BY answer,c.id ORDER BY c.id) contT GROUP BY contT.id
 */
@Controller
@RequestMapping("/admin/option")
public class AdminOptionController {
    private Log log = LogFactory.getLog(this.getClass());
    @Autowired
    UserOptionRepository userOptionRepository;
    @Autowired
    SessionHandler sessionHandler;
    @Autowired
    QuestionFormRepository questionFormRepository;
    @Autowired
    QuestionGroupRepository questionGroupRepository;
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    QuestionnaireRepository questionnaireRepository;
    @Autowired
    UserAnswersRepository userAnswersRepository;
    @Autowired
    QuestionAnswerRepository questionAnswerRepository;
    @Autowired
    UserRepository userRepository;

    @RequestMapping("/manageUserOption.jspa")
    public String manageUserOption(HttpServletRequest request, Model model, @RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam(value = "pageSize", defaultValue = "15") int pageSize
            , @RequestParam(value = "qVal", defaultValue = "") String qVal) {
        List<UserOption> options = userOptionRepository.queryOptions(qVal, pageSize * (page - 1), pageSize);
        model.addAttribute("options", options);
        model.addAttribute("pagingString",
                Pagination.getPagingString(userOptionRepository.queryOptionCount(qVal), pageSize, page, request));
        return "/admin/jspa/option/manageUserOption";
    }

    /**
     * 保存用户意见
     */
    @ResponseBody
    @RequestMapping(value = "/saveUserOption.jspx", method = RequestMethod.POST)
    public String saveUserOption(HttpSession session, @RequestParam("param") String param) {
        JSONObject object = JSONObject.fromObject(param);
        UserOption option = new UserOption();
        UserSession userSession = sessionHandler.getUserSession(session);
        option.setPhone(userSession.getCellPhone());
        option.setName(userSession.getUserName());
        option.setUserId(userSession.getUserId().toString());
        if (object.has("content")) {
            option.setContent(object.getString("content"));
        }
        User user = userRepository.findByUserId(userSession.getUserId());
        option.setDeptName(user.getDepartmentName());
        option.setAddTime(new Date());
        userOptionRepository.save(option);
        return ST.ok.toJson();
    }

    /**
     * 编辑表单
     */
    @RequestMapping("editQuestionForm.jspa")
    public String editQuestionForm(Model model, @RequestParam(value = "id", defaultValue = "-1") long id) {
        QuestionForm questionForm = questionFormRepository.findOne(id);
        if (questionForm != null) {
            model.addAttribute("questionForm", questionForm);
            List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<QuestionGroupAndQuestionWrap> groupAndQuestions = new ArrayList<>();
            for (QuestionGroup g : groups) {
                QuestionGroupAndQuestionWrap qg = new QuestionGroupAndQuestionWrap(g);
                List<Question> tempQs = new ArrayList<>();
                for (Question q : questions) {
                    if (g.getId() == q.getGroupId()) {
                        tempQs.add(q);
                    }
                }
                qg.setQuestions(tempQs);
                groupAndQuestions.add(qg);
            }
            model.addAttribute("groups", groupAndQuestions);
        }
        return "/admin/jspa/option/editQuestionForm";
    }

    /**
     * 保存表单
     */
    @ResponseBody
    @RequestMapping(value = "saveQuestionForm.jspa", method = RequestMethod.POST)
    public String saveQuestionForm(@RequestParam("param") String param) {
        JSONObject object = JSONObject.fromObject(param);
        QuestionForm questionForm = new QuestionForm();
        if (object.has("id")) {
            questionForm = questionFormRepository.findOne(object.getLong("id"));
            if (questionForm == null) {
                questionForm = new QuestionForm();
                Date now = new Date();
                questionForm.setAddTime(now);
            }
        }
        if (object.has("name")) {
            questionForm.setName(object.getString("name"));
        }
        questionFormRepository.save(questionForm);
        List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
        List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
        questionGroupRepository.delete(groups);
        questionRepository.delete(questions);
        if (object.has("groups")) {
            net.sf.json.JSONArray jsonArray = object.getJSONArray("groups");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jo = (JSONObject) jsonArray.get(i);
                QuestionGroup g = new QuestionGroup();
                g.setName(jo.getString("name"));
                g.setFormId(questionForm.getId());
                questionGroupRepository.save(g);
                net.sf.json.JSONArray questionArray = jo.getJSONArray("question");
                for (int j = 0; j < questionArray.size(); j++) {
                    JSONObject o = (JSONObject) questionArray.get(j);
                    Question q = new Question();
                    q.setFormId(questionForm.getId());
                    q.setGroupId(g.getId());
                    q.setGroupName(g.getName());
                    q.setTitle(o.getString("title"));
                    q.setOption1("满意");
                    q.setOption2("较满意");
                    q.setOption3("不满意");
                    /*net.sf.json.JSONArray choices = o.getJSONArray("choice");
                    if (null != choices && choices.size() > 0) {
                        if (choices.size() > 0 && !"".equals(choices.optString(0))) {
                            q.setOption1(choices.optString(0));
                        }
                        if (choices.size() > 1 && !"".equals(choices.optString(1))) {
                            q.setOption2(choices.optString(1));
                        }
                        if (choices.size() > 2 && !"".equals(choices.optString(2))) {
                            q.setOption3(choices.optString(2));
                        }
                        if (choices.size() > 3 && !"".equals(choices.optString(3))) {
                            q.setOption4(choices.optString(3));
                        }
                        if (choices.size() > 4 && !"".equals(choices.optString(4))) {
                            q.setOption5(choices.optString(4));
                        }
                        if (choices.size() > 5 && !"".equals(choices.optString(5))) {
                            q.setOption6(choices.optString(6));
                        }
                    }*/
                    questionRepository.save(q);
                }
            }
        }
        return ST.ok.toJson();
    }

    /**
     * 删除问题表单
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delQuestionForm.jspx")
    public String delQuestionForm(@RequestParam(value = "id", defaultValue = "-1") long id) {
        QuestionForm questionForm = questionFormRepository.findOne(id);
        if (questionForm != null) {
            int papersCount = questionnaireRepository.queryQuestionnairesCountByFormId(id);
            if (papersCount > 0) {
                return ST.dataHasChild.toJson();
            }
            List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            questionFormRepository.delete(questionForm);
            questionGroupRepository.delete(groups);
            questionRepository.delete(questions);
        } else {
            return ST.dataNotExists.toJson();
        }
        return ST.ok.toJson();
    }

    /**
     * 管理问卷
     *
     * @return
     */
    @RequestMapping("/manageQuestionnaire.jspa")
    public String manageQuestionnaire(HttpServletRequest request, Model model, @RequestParam(value = "dVal", defaultValue = "1970-01-01") String dVal
            , @RequestParam(value = "dVal2", defaultValue = "2090-12-12") String dVal2) {
        dVal += " 00:00:00";
        dVal2 += " 23:59:59";
        List<Questionnaire> questionnaires = questionnaireRepository.queryQuestionnaires(dVal, dVal2);
        model.addAttribute("questionnaires", questionnaires);
        return "/admin/jspa/option/manageQuestionnaire";
    }

    @RequestMapping("editQuestionnaire.jspa")
    public String editQuestionnaire(Model model, @RequestParam(value = "id", defaultValue = "-1") long id) {
        Questionnaire questionnaire = questionnaireRepository.findOne(id);
        if (questionnaire != null) {
            model.addAttribute("questionnaire", questionnaire);
        }
        return "/admin/jspa/option/editQuestionnaire";
    }

    /**
     * 保存问卷
     */
    @ResponseBody
    @RequestMapping(value = "saveQuestionnaire.jspa", method = RequestMethod.POST)
    public String saveRepairOrder(HttpSession session, @RequestParam("param") String param) throws ParseException {
        JSONObject object = JSONObject.fromObject(param);
        Questionnaire questionnaire = new Questionnaire();
        if (object.has("id")) {
            questionnaire = questionnaireRepository.findOne(object.getLong("id"));
            if (questionnaire == null) {
                questionnaire = new Questionnaire();
                questionnaire.setUserNum(0);
            }
        }
        if (object.has("name")) {
            questionnaire.setName(object.getString("name"));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (object.has("publishTime")) {
            String publishTime = object.getString("publishTime");
            questionnaire.setPublishTime(sdf.parse(publishTime));
        }
        if (object.has("endTime")) {
            String endTime = object.getString("endTime");
            questionnaire.setEndTime(sdf.parse(endTime));
        }
        if (object.has("formId")) {
            questionnaire.setFormId(object.getLong("formId"));
        }
        Date now = new Date();
        int state = 0;
        if (now.getTime() < questionnaire.getPublishTime().getTime()) {
            state = 0;
        } else if (questionnaire.getPublishTime().getTime() < now.getTime() && now.getTime() < questionnaire.getEndTime().getTime()) {
            state = 1;
        } else {
            state = 2;
        }
        questionnaire.setState(state);
        questionnaireRepository.save(questionnaire);
        return ST.ok.toJson();
    }

    /**
     * 问卷详情查看
     *
     * @param model
     * @param paperId
     * @return
     */
    @RequestMapping("viewQuestionnaire.jspa")
    public String viewQuestionnaire(Model model, @RequestParam(value = "id", defaultValue = "-1") long paperId) {
        Questionnaire paper = questionnaireRepository.findOne(paperId);
        if (null == paper) {
            return ST.dataNotExists.toJson();
        }
        model.addAttribute("questionnaire", paper);
        QuestionForm questionForm = questionFormRepository.findOne(paper.getFormId());
        if (questionForm != null) {
            model.addAttribute("questionForm", questionForm);
            List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<QuestionGroupAndQuestionWrap> groupAndQuestions = new ArrayList<>();
            for (QuestionGroup g : groups) {
                QuestionGroupAndQuestionWrap qg = new QuestionGroupAndQuestionWrap(g);
                List<Question> tempQs = new ArrayList<>();
                for (Question q : questions) {
                    if (g.getId() == q.getGroupId()) {
                        tempQs.add(q);
                    }
                }
                qg.setQuestions(tempQs);
                groupAndQuestions.add(qg);
            }
            model.addAttribute("groups", groupAndQuestions);
        }
        return "/admin/jspa/option/viewQuestionnaire";
    }

    /**
     * 问卷填写列表详情查看
     *
     * @return
     */
    @RequestMapping("manageUserAnswer.jspa")
    public String manageUserAnswer(Model model, @RequestParam(value = "id", defaultValue = "-1") long paperId) {
        Questionnaire paper = questionnaireRepository.findOne(paperId);
        if (null == paper) {
            return ST.dataNotExists.toJson();
        }
        List<UserAnswers> userAnswers = userAnswersRepository.findByQuestionnaireId(paperId);
        model.addAttribute("userAnswers", userAnswers);
        model.addAttribute("questionnaireId",paperId);
        return "/admin/jspa/option/manageUserAnswer";
    }
    /**
     * 个人答卷详情查看
     *
     * @return
     */
    @RequestMapping("viewUserAnswer.jspa")
    public String viewUserAnswer(Model model, @RequestParam(value = "id", defaultValue = "-1") long id) {
        UserAnswers  userAnswers = userAnswersRepository.findOne(id);
        if (null == userAnswers) {
            return ST.dataNotExists.toJson();
        }
        model.addAttribute("userAnswers", userAnswers);
        Questionnaire paper = questionnaireRepository.findOne(userAnswers.getQuestionnaireId());
        if (null == paper) {
            return ST.dataNotExists.toJson();
        }
        model.addAttribute("questionnaire", paper);
        QuestionForm questionForm = questionFormRepository.findOne(paper.getFormId());
        if (questionForm != null) {
            model.addAttribute("questionForm", questionForm);
            List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<QuestionGroupAndQuestionWrap> groupAndQuestions = new ArrayList<>();
            for (QuestionGroup g : groups) {
                QuestionGroupAndQuestionWrap qg = new QuestionGroupAndQuestionWrap(g);
                List<Question> tempQs = new ArrayList<>();
                for (Question q : questions) {
                    if (g.getId() == q.getGroupId()) {
                        tempQs.add(q);
                    }
                }
                qg.setQuestions(tempQs);
                groupAndQuestions.add(qg);
            }
            model.addAttribute("groups", groupAndQuestions);
            List<QuestionAnswer> questionAnswers = questionAnswerRepository.findByUserIdAndUserAnswerId(userAnswers.getUserId(),userAnswers.getId());
            model.addAttribute("questionAnswers",questionAnswers);
        }
        return "/admin/jspa/option/viewUserAnswer";
    }

    /**
     * 删除个人填写问卷
     */
    @ResponseBody
    @RequestMapping("delUserAnswer.jspa")
    public String delUserAnswer(Model model, @RequestParam(value = "id", defaultValue = "-1") long id) {
        UserAnswers userAnswers = userAnswersRepository.findOne(id);
        if (null == userAnswers) {
            return ST.dataNotExists.toJson();
        }
        Questionnaire questionnaire = questionnaireRepository.findOne(userAnswers.getQuestionnaireId());
        List<QuestionAnswer> questionAnswers = questionAnswerRepository.findByUserAnswerId(userAnswers.getId());
        userAnswersRepository.delete(userAnswers);
        questionAnswerRepository.delete(questionAnswers);
        questionnaire.setUserNum(questionnaire.getUserNum()>0?(questionnaire.getUserNum()-1):0);
        questionnaireRepository.save(questionnaire);
        return ST.ok.toJson();
    }

    /**
     * 删除问卷
     */
    @ResponseBody
    @RequestMapping("delQuestionnaire.jspa")
    public String delQuestionnaire(Model model, @RequestParam(value = "id", defaultValue = "-1") long paperId) {
        Questionnaire paper = questionnaireRepository.findOne(paperId);
        if (null == paper) {
            return ST.dataNotExists.toJson();
        }
        org.json.JSONObject jo = ST.ok.getJsonObject();
        QuestionForm questionForm = questionFormRepository.findOne(paper.getFormId());
        jo.put("paperName", paper.getName());
        if (questionForm != null) {
            /*List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            questionRepository.delete(questions);
            questionGroupRepository.delete(groups);*/
            /*questionFormRepository.delete(questionForm);*/
            List<UserAnswers> answerses = userAnswersRepository.findByQuestionnaireId(paperId);
            List<QuestionAnswer> questionAnswers = questionAnswerRepository.findByQuestionnaireId(paperId);
            userAnswersRepository.delete(answerses);
            questionAnswerRepository.delete(questionAnswers);
        }
        questionnaireRepository.delete(paper);
        return ST.ok.toJson();
    }


    /**
     * 导出问卷填写信息
     */
    @RequestMapping("/repairOrderExport.jspa")
    public void repairOrderExport(HttpServletRequest request, HttpServletResponse resp,
                                  @RequestParam(value = "questionnaireId", defaultValue = "") long questionnaireId) throws IOException {
        resp.setHeader("Content-Type", "application/octet-stream; charset=utf-8");
        OutputStream os = resp.getOutputStream();

        Questionnaire questionnaire = questionnaireRepository.findOne(questionnaireId);
        try {
            String name = (questionnaire==null?"问卷调查结果统计表":questionnaire.getName());
            log.info(name);
            int rowNum = 0;
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(name);

            List<Object[]> resutl = questionAnswerRepository.queryExportData(questionnaireId);
            if (resutl.size() > 0) {
                HSSFFont font = wb.createFont();
                font.setBold(true);
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                HSSFCellStyle style = wb.createCellStyle();
                style.setFont(font);
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0, 1).setCellValue("国投物业一分公司调查结果");
                row = sheet.createRow(rowNum++);
                String[] names = {"序号", "问题分组", "问题", "满意", "较满意", "不满意", "其他意见建议"};
                for (int i = 0; i < names.length; i++) {
                    row.createCell(i, 1).setCellValue(names[i]);
                }
                row.setRowStyle(style);
                int a = 1;

                for (Object[] objects : resutl) {
                    HSSFRow itemRow = sheet.createRow(rowNum++);
                    itemRow.createCell(0, 1).setCellValue(a);
                    itemRow.createCell(1, 1).setCellValue(objects[0].toString());
                    itemRow.createCell(2, 1).setCellValue(null == objects[1] ? "":objects[1].toString());
                    itemRow.createCell(3, 1).setCellValue(null==objects[3]?"":objects[3].toString());
                    itemRow.createCell(4, 1).setCellValue(null==objects[4]?"":objects[4].toString());
                    itemRow.createCell(5, 1).setCellValue(null==objects[5]?"":objects[5].toString());
                    itemRow.createCell(6, 1).setCellValue(null==objects[6]?"":objects[6].toString());
                    a++;
                }
            }
            resp.addHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes(), "iso-8859-1") + ".xls");
            wb.write(os);
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
            resp.addHeader("Content-Disposition", "attachment; filename*=UTF-8''error.txt");
            os.write("出错了，请重试".getBytes());
            os.write(e.getMessage().getBytes());
        }
        os.flush();
        os.close();
    }
}